package learn.doc;

import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PdfBoxUtil {


	/**
	 * 多图片合成pdf的限制后缀
	 */
	private static final List IMAGE_SUFFIX = Arrays.asList("jpg", "png", "jpeg");


	public static boolean pdf2Image(String sourceFile,String destFile,String uuid, String width,String pageScale){
		File file = new File(sourceFile);
		PDDocument pdDocument;
		try {
			String imgFolderPath = destFile;
			pdDocument = PDDocument.load(file);
			PDFRenderer renderer = new PDFRenderer(pdDocument);
			int numberOfPages = pdDocument.getNumberOfPages();
			for (int i = 0; i<numberOfPages;i++){
				/* dpi越大转换后越清晰，相对转换速度越慢 */
				StringBuffer imgFilePath = null;
				String imgFilePathPrefix = imgFolderPath + File.separator + uuid+ "_" +i;
				imgFilePath = new StringBuffer();
				imgFilePath.append(imgFilePathPrefix);
				imgFilePath.append(".png");
				File dstFile = new File(imgFilePath.toString());
				BufferedImage image = renderer.renderImageWithDPI(i, 50);
				ImageIO.write(image, "png", dstFile);
				System.out.println("PDF文档转PNG图片成功！");
			}
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static void imgToPdf(String imgFolder, String target) throws IOException{

//		PDDocument doc = new PDDocument();
//		//创建一个空的pdf文件
//		doc.save(target);

		PDPage page;
		PDImageXObject pdImage;
		PDPageContentStream contents;
		BufferedImage bufferedImage;
		String fileName;
		float w, h;
		String suffix;
		File tempFile;
		int index;

		File folder = new File(imgFolder);
		for (int i = 0; i < folder.listFiles().length; i++) {
			tempFile = folder.listFiles()[i];
			if (!tempFile.isFile()) {
				continue;
			}

			fileName = tempFile.getName();
			index = fileName.lastIndexOf(".");
			if (index == -1) {
				continue;
			}
			//获取文件的后缀
			suffix = fileName.substring(index + 1);

			String filenamePre = fileName.substring(0,index);

			//如果文件后缀不是图片格式,跳过当前循环
			if (!IMAGE_SUFFIX.contains(suffix)) {
				continue;
			}

			PDDocument doc = new PDDocument();
			//创建一个空的pdf文件
			String pdffile = target+"/"+filenamePre+".pdf";
			doc.save(pdffile);

			bufferedImage = ImageIO.read(folder.listFiles()[i]);
			//Retrieving the page
			pdImage = LosslessFactory.createFromImage(doc, bufferedImage);
			w = pdImage.getWidth();
			h = pdImage.getHeight();
			page = new PDPage(new PDRectangle(w, h));
			contents = new PDPageContentStream(doc, page);
			contents.drawImage(pdImage, 0, 0, w, h);
			System.out.println("Image inserted");
			contents.close();

			doc.addPage(page);

			//保存pdf
			doc.save(pdffile);
			//关闭pdf
			doc.close();
		}
		//保存pdf
//		doc.save(target);
//		//关闭pdf
//		doc.close();
	}

	/**
	 * 多个pdf合并成一个
	 * @param files
	 * @param targetPath
	 * @return
	 */
	public static File manyPdfToOne(List<File> files, String targetPath) {
		try {
			PDFMergerUtility mergePdf = new PDFMergerUtility();
			for (File f : files) {
				if (f.exists() && f.isFile()) {
					// 循环添加要合并的pdf
					mergePdf.addSource(f);
				}
			}
			// 设置合并生成pdf文件名称
			mergePdf.setDestinationFileName(targetPath);
			// 合并pdf
			mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
			return new File(targetPath);
		} catch (Exception e) {
			return null;
		}
	}


	public static void main(String[] args) throws IOException {
//		String sourceFile = "/Users/hayashika/Desktop/pdf/实战Java高并发程序设计（第2版）@www.java1234.com .pdf";
//		String destFile = "/Users/hayashika/Desktop/pdfing";
//
//		String fileName = UUID.randomUUID().toString().replace("-","");
//		pdf2Image(sourceFile,destFile,fileName,"300","1");


		String imgFolder = "/Users/hayashika/Desktop/pdfing";
		String target = imgFolder+"/aa.pdf";

//		imgToPdf(imgFolder,imgFolder);

		File file1 = new File("/Users/hayashika/Desktop/pdfing/1624112036967.pdf");
		File file2 = new File("/Users/hayashika/Desktop/pdfing/1624113313350.pdf");
		List<File> files = new ArrayList<>();
		files.add(file1);
		files.add(file2);


		manyPdfToOne(files,target);
	}



}
